﻿using System;
using System.Data;
using BonsaiScrum.Core.Domain;
using BonsaiScrum.Core.Domain.Shared;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;

namespace BonsaiScrum.Data.CustomTypes
{
    internal class TaskStatusType : IUserType
    {
        public object Assemble(object cached, object owner)
        {
            return DeepCopy(cached);
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Disassemble(object value)
        {
            return DeepCopy(value);
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public bool IsMutable
        {
            get { return false; }
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            string statusString = (string)NHibernateUtil.String.NullSafeGet(rs, names[0]);

            if (string.IsNullOrEmpty(statusString)) return null;

            try
            {
                TaskStatus status = Enumeration.FromName<TaskStatus>(statusString);
                return status;
            }
            catch (ArgumentException)
            {
                return null;
            }
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            if (value == null)
            {
                NHibernateUtil.String.NullSafeSet(cmd, null, index);
                return;
            }

            value = value.ToString(); // Call ToString() on Enumeration instance.
            NHibernateUtil.String.NullSafeSet(cmd, value, index);
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public Type ReturnedType
        {
            get { return typeof(TaskStatus); }
        }

        public SqlType[] SqlTypes
        {
            get
            {
                SqlType[] types = new SqlType[1];
                types[0] = new SqlType(DbType.String);
                return types;
            }
        }

        public new bool Equals(object x, object y)
        {
            if (x == null) return false;
            return x.Equals(y);
        }
    }
}
